import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/pay_model/plat_wallet_flow_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/investmoney/investmoney_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/withdraw/withdraw_page.dart';

class WalletPersonalController extends GetxController {
  final ScrollController scrollController = ScrollController();
  String channel = '';
  final activeTab = 'INCREASE'.obs;
  int pageNum = 1;
  int pageSize = 20;
  var billList = RxList<PlatWalletFlowItemModel>([]);
  final hasWallet = RxDouble(0);

  @override
  void onInit() {
    super.onInit();
    getPlatWallet();
    // 初始化逻辑
    channel =
        (Get.arguments['channel'] ?? '') == 'DEBIT_CARD' ? 'HUIFU' : 'DIN_PAY';

    getBillList();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getBillList(loadMore: true);
        getPlatWallet();
      }
    });
  }

  Future<void> getPlatWallet() async {
    await http.netFetch<dynamic>(
      PayUrl.getPlatWalletBalance,
      success: (res) {
        hasWallet.value = res.data ?? 0.00;
      },
    );
  }

  Future<void> handleRefresh() async {
    getBillList(loadMore: true);
    getPlatWallet();
    return;
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  changeTab(String code) {
    if (code == activeTab.value) {
      return;
    }
    activeTab.value = code;
    getBillList();
  }

  void withdraw() {
    // 提现逻辑
    Get.toNamed('${WithdrawPage.path}?type=1&channel=${channel}');
  }

  void investmoney() {
    Get.toNamed('${InvestmoneyPage.path}?type=1&channel=${channel}');
  }

  Future<void> getBillList({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    var params = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'type': activeTab.value,
    };

    try {
      await http.netFetch<PlatWalletFlowModel>(
        PayUrl.pagePlatWalletFlow,
        params: params,
        success: (result) {
          List<PlatWalletFlowItemModel> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            billList.clear();
          }
          billList.addAll(list);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
    }
  }
}
